<template>
  <div class="container">
    <div class="handle-box">
      <el-button
        type="success"
        icon="el-icon-plus"
        class="handle-del mr10"
        style="margin-right: 10px"
        @click="addOne"
        >增加</el-button
      >
      <el-select
        v-model="query.fkCourseName"
        filterable
        placeholder="请输入课程名称"
        style="width: 170px; margin-left: 10px"
      >
        <el-option label="所有课程" value=""></el-option>
        <el-option
          v-for="item in courses"
          :key="'query' + item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-input
        clearable
        v-model="query.examName"
        placeholder="考试名称"
        class="handle-input mr10"
        style="width: 200px; margin-left: 10px; margin-right: 10px"
      ></el-input>
      <el-button type="primary" icon="el-icon-search" @click="handleSearch"
        >搜索</el-button
      >
    </div>
    <div style="margin: 25px 0px">
      <el-table :data="examTables" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="考试名：">
                <span>{{ props.row.examName }}</span>
              </el-form-item>
              <el-form-item label="所属课程：">
                <span>{{ props.row.fkCourseName }}</span>
              </el-form-item>
              <el-form-item label="开考时间：">
                <span>{{ formatDate(null, null, props.row.beginTime) }}</span>
              </el-form-item>
              <el-form-item label="监考人员：">
                <el-tag
                  class="table-expand"
                  v-for="user in getProctors(props.row.workList)"
                  :key="props.row.id + '-' + user.id + '-' + user.workType"
                  >{{ user.fkUserName }}</el-tag
                >
              </el-form-item>
              <el-form-item label="结束时间：">
                <span>{{ formatDate(null, null, props.row.endTime) }}</span>
              </el-form-item>
              <el-form-item label="阅卷人员：">
                <el-tag
                  class="table-expand"
                  v-for="user in getExaminers(props.row.workList)"
                  :key="props.row.id + '-' + user.id + '-' + user.workType"
                  >{{ user.fkUserName }}</el-tag
                >
              </el-form-item>
              <el-form-item label="考试班级：">
                <el-tag
                  type="success"
                  class="table-expand"
                  v-for="classes in props.row.classList"
                  :key="props.row.id + '-class-' + classes.id"
                >
                  {{ classes.className }}
                </el-tag>
              </el-form-item>
              <el-form-item label="试卷列表：">
                <el-tag
                  type="info"
                  class="table-expand"
                  v-for="paper in props.row.paperList"
                  :key="props.row.id + '-' + paper.id"
                  >{{
                    paper.paperName +
                    (paper.remarks === "" ? "" : "(" + paper.remarks + ")")
                  }}</el-tag
                >
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="考试名" prop="examName"> </el-table-column>
        <el-table-column
          label="开考时间"
          prop="beginTime"
          :formatter="formatDate"
        ></el-table-column>
        <el-table-column
          label="结束时间"
          prop="endTime"
          :formatter="formatDate"
        ></el-table-column>
        <el-table-column label="状态" prop="status" align="center">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.status === 1">考试中</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === 2">已结束</el-tag>
            <el-tag v-else>未开始</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130" align="center">
          <template slot-scope="scope">
            <el-button
            v-if="scope.row.status === 0 || scope.row.status === 1"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              :disabled="scope.row.status === 0 ? false : true"
              >编辑</el-button
            >
            <el-button
            v-if="scope.row.status === 0 || scope.row.status === 1"
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              :disabled="scope.row.status === 0 ? false : true"
              >删除</el-button
            >
            <el-button
            v-if="scope.row.status === 2"
              type="text"
              icon="el-icon-tickets"
              @click="examScore(scope.$index, scope.row)"
              >查看结果</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      title="增加"
      :append-to-body="true"
      :visible.sync="addVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="755px"
    >
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="所属课程：" prop="exam.fkCourseName">
          <el-select
            class="form-item"
            v-model="form.exam.fkCourseName"
            filterable
            placeholder="请输入课程名称"
          >
            <el-option
              v-for="item in courses"
              :key="'add' + item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试班级：" prop="classes">
          <el-select
            class="form-item"
            v-model="form.classes"
            filterable
            multiple
            placeholder="请选择班级"
          >
            <div v-loading="classesLoading">
              <el-option
                v-for="classes in formClasses"
                :key="'formclasses' + classes.id"
                :label="classes.className"
                :value="classes.id"
              >
              </el-option>
            </div>
          </el-select>
        </el-form-item>
        <el-form-item label="考试名：" prop="exam.examName">
          <el-input
            class="form-item"
            type="text"
            v-model="form.exam.examName"
            @blur="examNameBlur"
          ></el-input>
          <p v-if="hasExamName" style="font-size: 5px; height: 8px; color: red">
            &nbsp;&nbsp;&nbsp;<i class="fa fa-question-circle" aria-hidden="true"></i
            >&nbsp;已有考试名，请重新输入，建议加上学年信息
          </p>
        </el-form-item>
        <el-form-item label="开始时间：" prop="exam.beginTime">
          <el-date-picker
            class="form-item"
            v-model="form.exam.beginTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="exam.endTime">
          <el-date-picker
            class="form-item"
            v-model="form.exam.endTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="监考人员：" prop="proctors">
          <el-select
            class="form-item"
            v-model="form.proctors"
            multiple
            filterable
            remote
            :reserve-keyword="false"
            placeholder="请输入用户名"
            :remote-method="remoteSelectUser"
            :loading="userLoading"
            @focus="userListFocus"
            @change="userListChange('proctors', $event)"
          >
            <el-option
              v-for="item in selectUsers"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            >
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                "手机：" + item.userPhone
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阅卷人员：" prop="examiners">
          <el-select
            class="form-item"
            v-model="form.examiners"
            multiple
            filterable
            remote
            :reserve-keyword="false"
            placeholder="请输入用户名"
            :remote-method="remoteSelectUser"
            :loading="userLoading"
            @focus="userListFocus"
            @change="userListChange('examiners', $event)"
          >
            <el-option
              v-for="item in selectUsers"
              :key="item.id"
              :label="item.userName"
              :value="item.id"
            >
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                "手机：" + item.userPhone
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="remarks">
          <el-input class="form-item" type="text" v-model="form.exam.remarks"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改"
      :append-to-body="true"
      :visible.sync="updateVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="755px"
    >
      <el-form ref="updateform" :model="updateform" label-width="120px">
        <el-form-item label="开始时间：" prop="beginTime">
          <el-date-picker
            class="form-item"
            v-model="updateform.beginTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="endTime">
          <el-date-picker
            class="form-item"
            v-model="updateform.endTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注：" prop="remarks">
          <el-input class="form-item" type="text" v-model="updateform.remarks"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSave">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="查看结果"
      :append-to-body="true"
      :visible.sync="showRstVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-row>
        <el-col>
          <el-tag class="cyh-tag">应参考人数</el-tag><el-tag class="cyh-tag" style="height:28px;line-height:26px" type="info">{{ examRst.totalStu }}</el-tag>
          <el-tag class="cyh-tag" style="margin-left:50px">缺考人数</el-tag><el-tag style="height:28px;line-height:26px" class="cyh-tag" type="info">{{ examRst.noTest.length }}</el-tag>
        </el-col>
      </el-row>
      <el-row style="margin-top:15px">
        <el-col>
          <el-tag class="cyh-tag" type="warning">缺考名单</el-tag>
          <el-tag style="margin-left:5px;height:28px;line-height:26px" class="cyh-tag" type="info" v-for="item in examRst.noTest" :key="item">{{ item }}</el-tag>
        </el-col>
      </el-row>
      <el-row style="margin-top:15px">
        <el-col>
          <el-table :data="examRst.stuScores" height="250" border style="width: 100%">
            <el-table-column prop="userName" label="姓名" center> </el-table-column>
            <el-table-column prop="totalScore" label="成绩" center>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import DateUtils from "../../utils/DateUtils.js";
var _this;
export default {
  data() {
    return {
      courses: [],
      addVisible: false,
      showRstVisible: false,
      examRst: {
        noTest: [],
        totalStu: "",
        stuScore: [],
      },
      formClasses: [],
      selectUsers: [],
      classesLoading: false,
      userLoading: false,
      hasExamName: false,
      form: {
        exam: {
          fkCourseName: "",
        },
        examinerList: [],
        proctorList: [],
      },
      updateVisible: false,
      updateform: {
        remarks: "",
        examUuid: "",
      },
      rules: {
        "exam.fkCourseName": [
          { required: true, message: "请选择所属课程！", trigger: "blur" },
        ],
        classes: [{ required: true, message: "请选择考试班级！", trigger: "blur" }],
        "exam.examName": [{ required: true, message: "请输入考试名！", trigger: "blur" }],
        "exam.beginTime": [
          { type: "date", required: true, message: "请选择开考时间！", trigger: "blur" },
        ],
        "exam.endTime": [
          { type: "date", required: true, message: "请选择结束时间！", trigger: "blur" },
        ],
        proctors: [
          { type: "array", required: true, message: "请选择监考人！", trigger: "blur" },
        ],
        examiners: [
          { type: "array", required: true, message: "请选择阅卷人！", trigger: "blur" },
        ],
      },
      query: {
        fkCourseName: "",
        examName: "",
      },
      examTables: [],
    };
  },
  methods: {
    //增加
    addOne() {
      this.addVisible = true;
    },
    //获取数据
    getData() {
      this.$post("/exam/getpage", this.query).then((res) => {
        if (res.code === 0) {
          this.examTables = res.data;
        } else {
          console.log(`获取数据失败 ${res.msg}`);
        }
      });
    },
    //搜索
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getData();
    },
    //获取课程
    getCourse() {
      this.$post("/course/byteacher", null).then((res) => {
        if (res.code === 0) {
          this.courses = res.data;
        }
      });
    },
    //格式化时间
    formatDate(row, column, cellValue) {
      return DateUtils.utc2beijing(cellValue);
    },
    //获取监考员名字列表
    getProctors(workList) {
      return workList.filter((item) => {
        return item.workType === "1" || item.workType === "3";
      });
    },
    //获取阅卷人员
    getExaminers(workList) {
      return workList.filter((item) => {
        return item.workType === "2" || item.workType === "3";
      });
    },
    //根据课程名获取对应班级
    getClassByCourse() {
      if (_this.form.exam.fkCourseName === "") {
        return;
      } else {
        this.$post("/course/getclassbycourse", {
          courseName: _this.form.exam.fkCourseName,
        }).then((res) => {
          if (res.code === 0) {
            _this.formClasses = res.data;
            _this.classesLoading = false;
          }
        });
      }
    },
    //获取用户选择列表
    remoteSelectUser(query) {
      if (query === "" || query === null) {
        return;
      }
      this.userLoading = true;
      this.$post("/user/getuserselect", { userName: query }).then((res) => {
        if (res.code === 0) {
          this.selectUsers = res.data;
          this.userLoading = false;
        }
      });
    },
    //获取焦点事件
    userListFocus(ev) {
      this.selectUsers = [];
    },
    userListChange(type, val) {
      console.log("user---", val);
      if (type === "examiners") {
        if (this.form.examiners.length > this.form.examinerList.length) {
          // 增加
          let item = this.selectUsers.find((item) => {
            return item.id === val[val.length - 1];
          });
          this.form.examinerList.push(item);
        } else {
          //减少
          let temp = this.form.examinerList.filter((item) => {
            return val.indexOf(item.id) > -1;
          });
          this.form.examinerList = temp;
        }
        console.log("userselectUsers---", this.selectUsers);
        console.log("examinerList---", this.form.examinerList);
      }
      if (type === "proctors") {
        if (this.form.proctors.length > this.form.proctorList.length) {
          // 增加
          let item = this.selectUsers.find((item) => {
            return item.id === val[val.length - 1];
          });
          this.form.proctorList.push(item);
        } else {
          //减少
          let temp = this.form.proctorList.filter((item) => {
            return val.indexOf(item.id) > -1;
          });
          this.form.proctorList = temp;
        }
        console.log("userselectUsers---", this.selectUsers);
        console.log("examinerList---", this.form.proctorList);
      }
    },
    examNameBlur() {
      let query = this.form.examName;
      if (query === "" || query === null) {
        this.hasExamName = false;
        return;
      }
      this.$post("/exam/checkname", { examName: query }).then((res) => {
        if (res.code === 0) {
          this.hasExamName = res.data;
        }
      });
    },
    //保存考试
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.exam.beginTime >= this.form.exam.endTime) {
            this.$message.error("结束时间应晚于考试时间！");
            return;
          }
          if (this.form.exam.endTime - this.form.exam.beginTime < 1000 * 60 * 30) {
            this.$message.error("考试时长应大于30分钟！");
            return;
          }
          this.$post("/exam/add", this.form).then((res) => {
            if (res.code === 0) {
              this.$message.success("保存成功！");
              this.$refs.form.clearValidate();
              this.addVisible = false;
              this.form = {
                exam: {
                  fkCourseName: "",
                },
                examinerList: [],
                proctorList: [],
              };
              this.getData();
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      });
    },
    //删除
    handleDelete(index, row) {
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          _this.$post("/exam/delete", [row.examUuid]).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功！");
              _this.getData();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    //编辑
    handleEdit(index, oldrow) {
      let row = JSON.parse(JSON.stringify(oldrow));
      this.updateform.remarks = row.remarks;
      this.updateform.examUuid = row.examUuid;
      this.updateVisible = true;
    },
    editSave() {
      if (this.updateform.beginTime === "" || this.updateform.endTime === "") {
        this.$message.error("请选择时间！");
        return;
      }
      if (this.updateform.beginTime >= this.updateform.endTime) {
        this.$message.error("结束时间应晚于考试时间！");
        return;
      }
      if (this.updateform.endTime - this.updateform.beginTime < 1000 * 60 * 30) {
        this.$message.error("考试时长应大于30分钟！");
        return;
      }
      this.$post("/exam/update", this.updateform).then((res) => {
        if (res.code === 0) {
          this.$message.success("保存成功！");
          this.updateVisible = false;
          this.updateform = {};
          this.getData();
        } else {
          this.$message.error("保存失败");
        }
      });
    },
    examScore(index, row) {
      _this.$post("/exam/examrst", { examUuid: row.examUuid }).then((res) => {
        if (res.code === 0) {
          console.log(res);
          _this.examRst = res.data;
        } else {
          this.$message.error("查询失败！");
        }
      });
      _this.showRstVisible = true;
    },
  },
  created() {
    _this = this;
    this.getData();
    this.getCourse();
  },
  computed: {},
  watch: {
    "form.exam.fkCourseName": {
      handler(newval, oldval) {
        _this.classesLoading = true;
        _this.formClasses = [];
        _this.form.classes = [];
        _this.getClassByCourse();
      },
    },
  },
  mounted() {},
};
</script>
<style scoped>
.red {
  color: #ff0000;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.table-expand {
  display: inline-block;
  margin: 0px 5px 0 0;
  font-size: 14px;
}
.form-item {
  width: 400px;
}
.cyh-tag {
    display: inline-block;
    padding: 0 10px;
    height: 32px;
    line-height: 30px;
    font-size: 12px;
    border-radius: 4px;
    box-sizing: border-box;
    border: 1px solid rgba(64,158,255,.2);
    white-space: nowrap;
    margin-right:5px;
}
</style>
